<script lang="tsx">
import { Input, RadioGroup, Textarea, InputNumber } from 'ant-design-vue'
import { h, ref, onMounted, inject } from 'vue'
import { activityConfig, visibilityHandler } from '../activityConfig.js'
export default {
  props: {
    isDetail: {
      type: Boolean,
      default: false
    }
  },
  setup(props, { attrs, emit, expose, slots }){
    // 表单实例
    const activityShareFormRef = ref()
    onMounted(async () => {
    })

    // 接收父组件的创建活动的详细参数
    let activityDetailInfoInject: any = inject('activityDetailInfo')
    let activityDetailInfo: any = activityDetailInfoInject.value
    // 接收活动模板
    let activityTemplateDataRef : any = inject('activityTemplateData')
    let activityTemplateData : any = activityTemplateDataRef.value
    // activityShareChange 是否修改过表单
    let activityShareChangeInject: any = inject('activityShareChange')

    // 表单规则（总） 默认所有字段必填 根据具体活动 某些字段可以不填 需要在组件挂载时合并传递过来的规则
    const formRules = ref({
      shareText: [{ required: true, message: '请输入分享文案', trigger: ['blur'] }],
      shareImgAppMessage: [{ required: true, message: '请上传分享图片', trigger: ['blur'] }],
      shareImgTimeline: [{ required: true, message: '请上传分享图片', trigger: ['blur'] }],
      shareSuccessStandard: [{ required: true, message: '请选择分享成功标准', trigger: ['blur'] }],
      shareMaxNum: [{ required: true, message: '请输入最大允许分享次数', trigger: ['blur'] }],
      sharePeriodType: [{ required: true, message: '请选择同一用户周期性分享次数限制类型', trigger: ['blur'] }],
      sharePeriodTimes: [{ required: true, message: '请输入同一用户周期性限制分享次数', trigger: ['blur'] }],
      toShareMaxNum: [{ required: true, message: '请输入被分享人最大允许助力次数', trigger: ['blur'] }],
      toSharePeriodType: [{ required: true, message: '请选择同一用户周期性助力次数限制类型', trigger: ['blur'] }],
      toSharePeriodTimes: [{ required: true, message: '请输入同一用户周期性限制助力次数', trigger: ['blur'] }],
      exchangeType: [{ required: true, message: '请选择奖品兑换类型', trigger: ['blur'] }]
    })
    // 图片上传
    const ImgUpload = (item: any) => {
      return (
        <a-form-item label={item.label} name={item.name}>
          <GzUpload v-model:src={activityDetailInfo.activityShare[item.name]} disabled={props.isDetail} bizType={item.bizType} />
          { item.tip && <span class="gz-tip-text">{ item.tip }</span> }
        </a-form-item>
      )
    }
    // 组件映射表：将配置中的字符串映射到实际组件
    const componentMap = {
      // 基础组件
      'a-input': Input,  // 输入框
      'a-input-number': InputNumber,  // 数字输入框
      'a-radio-group': RadioGroup,  // 单选框
      'a-textarea': Textarea,  // 多行文本框

      // 自定义组件 -- 具有通用性
      'c-img-upload': ImgUpload,  // 图片上传
    }

    /**
     * 修改表单项的值
     * 统一处理：但是需要区分 有些表单的值在e.target.value  有些表单的值是e
     */
    const onChangeHandle = (e: any, name: string, tag: string) => {
      if(e === null || e === undefined){
        activityDetailInfo.activityShare[name] = null
        // 特殊字段的关联清理
        return
      }
      // 提取值的统一处理
      const value = e && typeof e === 'object' && 'target' in e
        ? e.target.value
        : e
      // 通用赋值
      activityDetailInfo.activityShare[name] = value
      // 特殊字段的额外处理
    }

    // 表单校验事件
    async function validateFields(isDraft) {
      return new Promise((resolve, reject) => {
        if(!activityShareChangeInject.value && isDraft){  // 表单没有修改过 且 是草稿 则不校验表单信息 提交处，也需要把该信息删除
          resolve()
          return
        }
        activityShareFormRef.value.validateFields(isDraft ? ['shareText', 'shareImgAppMessage', 'shareMaxNum', 'toShareMaxNum'] : undefined).then(() => {
          resolve()
        }).catch(err => {
          console.log('activityShare error', err)
          reject('请完善活动分享配置')
        })
      })
    }
    // 表单重置事件
    function clearValidate() {
      if (activityShareFormRef.value !== undefined) {
        activityShareFormRef.value.clearValidate()
      }
    }

    // 暴露表单校验事件
    expose({
      validateFields,
      clearValidate
    })

    return () => (
      <a-form
        ref={activityShareFormRef}
        class="form"
        label-col={{ span: 4 }}
        wrapper-col={{ span: 8 }}
        model={activityDetailInfo.activityShare}
        rules={formRules.value}
      >
      {activityConfig.activityShare.basefield.filter((item : any) => {
        // 过滤掉不在可用模板的字段
        return !item.usedTemplate?.length || item.usedTemplate.includes(activityTemplateData.activityTemplateNo)
      }).filter((item : any) => {
        return visibilityHandler(item.visibilityRules, activityDetailInfo.activityShare)
      }).map((item : any, index: number) => { 
        if(!item.component){
          return (
            <a-form-item
              key={`${item.name}_${index}`}
              name={item.name}
              label={item.label}
            >
              { h(componentMap[item.tag], {
                ...item,
                disabled: item.disabled || props.isDetail,
                value: activityDetailInfo.activityShare[item.name],
                onChange: (e) => onChangeHandle(e, item.name, item.tag)
              })}
            </a-form-item>
          )
        }else {
          // 处理 自定义 类型的组件
          return typeof componentMap[item.component] === 'function' ? componentMap[item.component](item) : componentMap[item.component]
        }
      })}
      </a-form>
    )
  }
}

</script>

<style lang="less" scoped>
.form{
  margin-left: 20px;
  margin-top: 20px;
  height: 100%;
  overflow-y: auto;
  &::-webkit-scrollbar{
    display: none;
  }
}
:deep(.ant-input-number) {
  width: 100%;
}
</style>